import requests
from loguru import logger
import json
import time
import random
from work.search_site_list import get_site_id

# def add_key(keys_word, company_info, matching_account):
#     cookies = matching_account['cookies']
#     matching_project = get_site_id(company_info=company_info, user=matching_account)
#     if matching_project == 0:
#         return f"账号: {matching_account['account']} -----> 没有 {company_info['company_name']} 该项目"
#     url = "https://online.seranking.com/api.keywords.html"
#     params = {
#         "do": "add"
#     }
#     total_keys = len(keys_word)
#     chunk_size = 500
#     success_count = 0
#
#     for i in range(0, total_keys, chunk_size):
#         # 获取当前块的关键词列表
#         chunk_keys = keys_word[i:i + chunk_size]
#         data = {
#             "site_id": str(matching_project['site_id']),
#             "is_new_site": "false",
#             "group_id": str(matching_project['group_id']),
#             "keys": json.dumps(chunk_keys),
#             "allow_duplicates": "0"
#         }
#
#         res = requests.post(url, params=params, data=data, cookies=cookies)
#         if res.status_code == 200:
#             data = res.json()
#             if data.get("data"):
#
#                 logger.success(f"{matching_project['company_name']} ------>  添加成功关键词: {data['data']['added']}")
#                 return int(data['data']['added'])
#             else:
#                 logger.error(f"{matching_project['company_name']} ----> 添加关键词失败: {data['error']}")
#                 return data['error']
#         elif res.status_code == 403:
#             logger.error(f"{matching_account['account']} -----> 账号cookies信息已失效")
#             return 0
#         else:
#             logger.error(f"{company_info['company_name']}: 添加关键词失败 ----> {res.json()} {res.status_code}")
#             return res.json()['error']


def add_key(keys_word, company_info, matching_account):
    cookies = matching_account['cookies']
    matching_project = get_site_id(company_info=company_info, user=matching_account)
    if matching_project == 0:
        return f"账号: {matching_account['account']} -----> 没有 {company_info['company_name']} 该项目"
    url = "https://online.seranking.com/api.keywords.html"
    params = {
        "do": "add"
    }
    data = {
        "site_id": str(matching_project['site_id']),
        "is_new_site": "false",
        "group_id": str(matching_project['group_id']),
        "keys": json.dumps(keys_word),
        "allow_duplicates": "0"
    }
    retry_count = 0
    while retry_count < 3:
        try:
            res = requests.post(url, params=params, data=data, cookies=cookies, timeout=5)
        except Exception as e:
            logger.error(f"{matching_account['account']}: {company_info['company_name']} ----> 请求超时: {e}")
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        if res.status_code == 200:
            data = res.json()
            if data.get("data"):
                logger.success(f"{matching_project['company_name']} ------>  添加成功关键词: {data['data']['added']}")
                return int(data['data']['added'])
            else:
                logger.error(f"{matching_project['company_name']} ----> 添加关键词失败: {data['error']}")
                return data['error']
        elif res.status_code == 403:
            logger.error(f"{matching_account['account']} -----> 账号cookies信息已失效")
            return 0
        else:
            logger.error(f"{company_info['company_name']}: 添加关键词失败 ----> {res.json()} {res.status_code}")
            return res.json()['error']
    return '请求超时'